﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SQLCE.Data;
using SQLCE.Entity;
using System.Linq.Expressions;

namespace SQLCE.Service
{
    public class ProductManager
    {
        IRepository<Product> _ProductRepository;
        IRepository<User_Info> _user_InfoRepository;
        public ProductManager(IRepository<Product> productRepository, IRepository<User_Info> user_InfoRepository)
        {
            _ProductRepository = productRepository;
            _user_InfoRepository = user_InfoRepository;
        }
        public List<Product> GetProduct(Expression<Func<User_Info, bool>> predicate)
        {
            var linq = _user_InfoRepository.Table;
            if (predicate != null)
                linq = linq.Where(predicate);

            var res = from data1 in _ProductRepository.Table
                   join data2 in linq on data1.UserID equals data2.ID
                   select new Product_Ext
                   {
                       ID = data1.ID,
                       UserID = data1.UserID,
                       Name = data1.Name,
                       User_Info = data2,
                       Price = data1.Price,
                   };
            return res.ToList<Product>();
        }

        public Product GetProduct(int id)
        {
            return _ProductRepository.Get(id);
        }

        public void UpdateProduct(Product entity)
        {
            //_ProductRepository.AddColumn(i => i.Name)
            //                  .AddColumn(i => i.Price)
            //                  .AddColumn(i => i.Reserve)
            //                  .AddColumn(i => i.UserID);
            //_ProductRepository.Update(entity);


            _ProductRepository.Update(i => new Product
            {
                Name = entity.Name,
                Price = entity.Price,
                Reserve = entity.Reserve,
                UserID = entity.UserID,
                ID = entity.ID,
            });
            _ProductRepository.SaveChanges();
        }

        public void DeleteProduct(int id)
        {
            _ProductRepository.Delete(_ProductRepository.Get(id));
            _ProductRepository.SaveChanges();
        }
    }
}